
import { connect } from 'react-redux';
import { useEffect, useState } from 'react';
import { Layout, Spin } from 'antd';

import HeaderContent from '../../components/headerContent';
import GroupList from '../../components/groupList';
import ChatContent from '../../components/chatContent';
import GroupDetail from '../../components/groupDetail';

import {
    wrapper,
    wrapper_content,
    room_wrapper,
    room_left,
    room_right,
} from './index.module.css'
import { changeCurrentItem } from '../../store/actions'
import { exitSocket, offSocketSystemMessage, onSocketSystemMessage } from '../../socketEvent';
import { publish } from 'pubsub-js';
import { systemMessage } from '../../event-type';

const { Header, Sider, Content } = Layout;



function Room(props) {

    const { user, islogin, changeCurrentItem } = props;

    const [loading, setLoading] = useState(true);


    useEffect(() => {
        changeCurrentItem('room');
    }, [changeCurrentItem]);

    useEffect(() => {
        if (user.id === -1 && !islogin) return;
        setLoading(false);
		
		// 如果在groupList和messageContent中分别监听,会使先出现的组件监听不到
		// 因为后出现的组件在useEffect的回调函数中会将socket监听解绑
        onSocketSystemMessage(user.id, data => {
			publish(systemMessage, data);
		});
		return () => {
			offSocketSystemMessage(user.id);
		}
    }, [user.id, islogin]);

	useEffect(() => {
		return () => {
			console.log('room destory')
			exitSocket();
		}
	}, []);


    return (
        <>
			<Layout className={wrapper}>
				<Header className="header">
					<HeaderContent />
				</Header>
				<Content className={`${wrapper_content} align_self_center`}>
					{
						loading ?  
							<div className="mask">
								<Spin spinning={loading} size='large' />
							</div> : 
							<Layout className={room_wrapper}>
								<Sider className={room_left} width={280}>
									<GroupList />
								</Sider>
								<Content className={room_right}>
									<ChatContent />
								</Content>
							</Layout>
					}
				</Content>
			</Layout>
			<GroupDetail />
		</>
    )
}

function mapStateToProps(state) {
	return {
		islogin: state.islogin,
		user: state.user,
	}
}
export default connect(
    mapStateToProps,
    {
        changeCurrentItem,
    }
)(Room);



